package hu.rsc.feeds.server;

import hu.rsc.feeds.client.data.GeneratedFeed;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.output.XMLOutputter;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;

public class AtomServlet extends HttpServlet {

    private static final long serialVersionUID = 1268908910096781069L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
	Long id = 0l;
	try {
	    id = Long.parseLong(request.getParameter("channel"));
	} catch (Exception e) {

	}
	final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	GeneratedFeed feed = new GeneratedFeed();
	feed.setAuthor("Red Staff Corporation");
	feed.setPubDate(new Date());
	feed.setTitle("Feed is not available.");
	try {
	    Entity e = datastore.get(KeyFactory.createKey(RssReaderServiceImpl.TABLE_GENERATED_FEED, id));
	    feed.setAuthor((String) e.getProperty(GeneratedFeed.PROP_AUTHOR));
	    feed.setTitle((String) e.getProperty(GeneratedFeed.PROP_TITLE));
	    feed.setPubDate((Date) e.getProperty(GeneratedFeed.PROP_PUB_DATE));
	    feed.setId(id);
	} catch (EntityNotFoundException e1) {
	    // TODO Auto-generated catch block
	    e1.printStackTrace();
	}
	AtomGenerator ag = new AtomGenerator(feed, false);

	XMLOutputter outputter = new XMLOutputter();
	response.setContentType("text/xml");
	try {
	    outputter.output(ag.getDocument(), response.getOutputStream());
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

    }

}
